package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.PageObject;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Transactional(readOnly = false,
                rollbackFor = Throwable.class
                /*,noRollbackFor = */
                ,isolation = Isolation.READ_COMMITTED,
                timeout = 5,
                propagation = Propagation.REQUIRED)//readOnly默认为false
@Service
public class SysUserServiceImpl implements SysUserService{
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    /**
     * @RequiredLog注解描述的方法为日志切入点方法
     * @param username
     * @param pageCurrent
     * @return
     */
    @RequiredLog("日志分页查询")
    @Override
    public PageObject<SysUser> findPageObjects(String username, Integer pageCurrent) {
        String tName = Thread.currentThread().getName();
        System.out.println("====================="+tName);
        int pageSize=5;
        Page<SysUser> page = PageHelper.startPage(pageCurrent, pageSize);
        List<SysUser> records=sysUserDao.findPageObjects(username);
        return new PageObject<>((int)page.getTotal(),records,
                pageSize,pageCurrent);
    }

    /**
     * @RequiresPermissions注解描述的方法为事务的切入点方法
     *此方法在执行时需要在通知方法中判断用户是否有访问此方法的权限
     * （检查用户权限是否包含@RequiresPermissions注解内部包含的权限）
     * ，假如有权限则授权访问
     * @param id
     * @param valid
     * @return
     */
    @RequiresPermissions("sys:user:update")
    @Override
    public int validById(Integer id, Integer valid) {
        int rows = sysUserDao.validById(id, valid);
        if(rows==0)
            throw new ServiceException("记录可能不存在");
        return rows;
    }

    @Override
    public int saveObject(SysUser entity, Integer[] roleIds) {
        //try{Thread.sleep(10000);}catch (Exception e){}
        //参数校验（省略）
        //产生一个随机字符串作为加密盐
        String salt = UUID.randomUUID().toString();
        //对密码进行MD5盐值加密（MD5特点：不可逆（可加密，不可解密），相同内容加密结果也相同）
        System.out.println(entity.getPassword());
        SimpleHash sh = new SimpleHash("MD5", entity.getPassword(), salt, 1);
        String hashedPassword = sh.toHex();
        entity.setSalt(salt);
        entity.setPassword(hashedPassword);
        int rows = sysUserDao.saveObject(entity);
        sysUserRoleDao.insertObject(entity.getId(),roleIds);
        return rows;

    }

    //@Transactional注解描述的方法为事务的切入点方法
    //此方法在执行时就会通过通知方法为其进行事务逻辑增强
    @Transactional(readOnly = true)
    @Override
    public Map<String, Object> findById(Integer id) {
        SysUser user = sysUserDao.findById(id);
        if(user==null)
            throw new ServiceException("用户可能已经不存在");
       List<Integer> roleIds=sysUserRoleDao.findRoleIdsByUserId(id);
       Map<String,Object> map=new HashMap<>();
       map.put("user", user);
       map.put("roleIds", roleIds);
        return map;
    }

   /* @Override
    public SysUserRole findById(Integer id) {
        SysUserRole userRole = sysUserDao.findById(id);
        if(userRole==null)
            throw new ServiceException("记录可能已经不存在");
        return userRole;
    }*/


    @Override
    public int updateObject(SysUser entity, Integer[] roleIds) {
        int rows = sysUserDao.updateObject(entity);
        if(rows==0)
            throw  new ServiceException("记录可能已经不存在了");
        sysUserRoleDao.deleteObjectByUserId(entity.getId());
        //rows=sysUserRoleDao.deleteObjectByUserId(entity.getId());
        //if(rows>0)throw new ServiceException("更新异常");
        sysUserRoleDao.insertObject(entity.getId(),roleIds);
        return rows;
    }


}
